package com.zijiebutiao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zijiebutiao.dtos.TOrderDto;
import com.zijiebutiao.pojos.TMember;
import com.zijiebutiao.pojos.TOrder;
import com.zijiebutiao.pojos.TOrdersetting;
import com.zijiebutiao.pojos.TSetmeal;
import com.zijiebutiao.service.TMemberService;
import com.zijiebutiao.service.TOrderService;
import com.zijiebutiao.service.TOrdersettingService;
import com.zijiebutiao.service.TSetmealService;
import com.zijiebutiao.utils.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Date 2023/3/6 20:23
 * @Author 时间刺客
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("/setmeal")
@Api(tags = "预约列表")
public class TOrderController {
    @Autowired
    private TOrderService tOrderService;

    @Autowired
    private TSetmealService tSetmealService;

    @Autowired
    private TMemberService tMemberService;

    @Autowired
    private TOrdersettingService tOrdersettingService;

    @GetMapping("/delorder/{id}")
    @ApiOperation(value = "取消预约",notes = "",response = boolean.class)
    public ResultVo delOrder(@PathVariable(name = "id") Integer id){

        return ResultVo.success(tOrderService.removeById(id));
    }
    @ApiOperation(value = "确认预约",notes = "",response = boolean.class)
    @GetMapping("/editstatus/{id}/{date}")
    public ResultVo editStatus(@PathVariable(name = "id") Integer id,@PathVariable(name = "date") String date) throws ParseException {
        TOrdersetting ordersetting = tOrdersettingService.getOne(Wrappers.lambdaQuery(TOrdersetting.class).eq(TOrdersetting::getOrderdate, date));
        if (ordersetting==null){
            TOrdersetting tOrdersetting=new TOrdersetting();
            Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            tOrdersetting.setOrderdate(parse);
            tOrdersetting.setNumber(100);
            tOrdersetting.setReservations(1);
            tOrdersettingService.save(tOrdersetting);
        }else {
            if (ordersetting.getReservations()>=ordersetting.getNumber()){
                return ResultVo.error(500,"请先增加可约预约人数后再确认预约!");
            }
            Integer reservations = ordersetting.getReservations();
            reservations=reservations==null?0:reservations;
            reservations++;
            ordersetting.setReservations(reservations);
            boolean b = tOrdersettingService.updateById(ordersetting);
        }
        TOrder tOrder=new TOrder();
        tOrder.setId(id);
        tOrder.setOrderstatus("到诊");
        return ResultVo.success(tOrderService.updateById(tOrder));
    }
    @ApiOperation(value = "新建预约",notes = "",response = boolean.class)
    @PostMapping("/createorder/{id}")
    public ResultVo createOrder(@PathVariable(name = "id")Integer id,@RequestBody Map map) throws ParseException {
        if (map==null||id<=0) {
            return ResultVo.error(500,"信息错误，失败！");
        }
        boolean b = tOrderService.creatOrder(id, map);
        if (b){
            return ResultVo.success(b);
        }
        return ResultVo.error(500,"信息错误或您当前日期内已预约过！失败！");
    }
    @ApiOperation(value = "预约列表分页与搜索",notes = "",response =PageInfo.class)
    @PostMapping("/findPage")
    public ResultVo findPage(@RequestBody Map map) throws ParseException {
            Integer currentPage=1;
            Integer pageSize=10;
            if (map.get("currentPage")!=null||map.get("pageSize")!=null){
                currentPage= (Integer) map.get("currentPage");
                pageSize= (Integer) map.get("pageSize");
            }

            List<TOrder> list=null;
            LambdaQueryWrapper<TOrder> wq=Wrappers.lambdaQuery();
            wq.orderByDesc(TOrder::getId);
            if (map.get("queryString")==null||"".equals(map.get("queryString"))){
                PageHelper.startPage(currentPage,pageSize);
                list = tOrderService.list(wq);

            }else {

                TMember member = tMemberService.getOne(
                        Wrappers.lambdaQuery(TMember.class)
                                .eq(TMember::getName, map.get("queryString")).or()
                                .eq(TMember::getPhonenumber, map.get("queryString")).or()
                                .eq(TMember::getFilenumber, map.get("queryString"))
                );
                if (member==null){
                    return ResultVo.error(500,"查询信息错误，没有查到！");
                }

                PageHelper.startPage(currentPage,pageSize);
                wq.eq(TOrder::getMemberId,member.getId());
                list = tOrderService.list(wq);
            }

            ArrayList<TOrderDto> arrayList = new ArrayList<>();
            list.stream().forEach(s->{
                TMember one = tMemberService.getOne(Wrappers.lambdaQuery(TMember.class).eq(TMember::getId, s.getMemberId()));
                TOrderDto tOrderDto= new TOrderDto();
                tOrderDto.setId(s.getId());
                tOrderDto.setOrderdate( s.getOrderdate());
                tOrderDto.setOrderstatus(s.getOrderstatus());
                tOrderDto.setOrdertype(s.getOrdertype());
                tOrderDto.setMemberId( s.getMemberId());
                tOrderDto.setSetmealId(s.getSetmealId());
                tOrderDto.setName(one.getName());
                tOrderDto.setPhonenumber(one.getPhonenumber());
                tOrderDto.setFilenumber(one.getFilenumber());
                arrayList.add(tOrderDto);
            });

            PageInfo<TOrder> pageInfo = new PageInfo<>(list);
            PageInfo<TOrderDto> pageInfoTorder = new PageInfo<>(arrayList);
            pageInfoTorder.setTotal(pageInfo.getTotal());
            return ResultVo.success(pageInfoTorder);
    }

    @ApiOperation(value = "查询所有套餐",notes = "",response = PageInfo.class)
    @GetMapping("/findAll/{currentPage}/{pageSize}")
    public ResultVo page(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize){
        //健壮性判断
        if (currentPage==null || currentPage<=0){
            currentPage = 1;
        }
        if (pageSize==null || pageSize<=0){
            pageSize = 4;
        }

//        //数据库的分页查询
//        IPage<Student> page = new Page<>(currentPage,pageSize);
//        //使用mybatisplus的分页插件，实现分页查询
//        studentService.page(page);

        //数据库的分页查询 pageHelper
        PageHelper.startPage(currentPage,pageSize);
        List<TSetmeal> setmeals=tSetmealService.list();
        PageInfo<TSetmeal> pageInfo=new PageInfo<>(setmeals);
        return ResultVo.success(pageInfo);
    }
    @ApiOperation(value = "套餐分页查询",notes = "",response = PageInfo.class)
    @GetMapping("/searchtc/{name}/{currentPage}/{pageSize}")
    public ResultVo searchtc(@PathVariable(name = "name") String name,@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize){
        //数据库的分页查询 pageHelper
        PageHelper.startPage(currentPage,pageSize);
        LambdaQueryWrapper<TSetmeal> wq= Wrappers.lambdaQuery();
        wq.like(true,TSetmeal::getName,name);
        List<TSetmeal> setmeals = tSetmealService.list(wq);
        PageInfo<TSetmeal> pageInfo=new PageInfo<>(setmeals);
        return ResultVo.success(pageInfo);
    }
}
